<?php

class RESTfulView{
	
	/**
	 * Function to get Request type
	 * @access public
	 * @param - 
	 * @return string, get, post, put, delete
	 */
	function getRequestType(){
		if(isset($_SERVER['REQUEST_METHOD'])){
			return strtolower($_SERVER['REQUEST_METHOD']);
		}
		return null;
	}
	
	/**
	 * Function to get requested URI
	 * @access public
	 * @param -
	 * @return  string
	 */
	function getRequestedResource(){
		if(isset($_SERVER['PATH_INFO'])){
			$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
			return $request;
		}
		return null;
	}
	
	/**
	 * Function to get ProducerId from get, post or put
	 * @access public
	 * @param -
	 * @return ProducerId
	 */
	function getRequestedProducerId(){
		if(isset($_SERVER['PATH_INFO'])){
			$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
			if(count($request) >= 3){
				return (int)$request[2];
			}
		}
		return null;
	}
	
	/**
	 * Function to get requested responsetype
	 * @access public
	 * @param -
	 * @return XML/JSON (if none given, XML is default)
	 */
	function getRequestResponseType(){
		$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
		if($request[count($request)-1] == "json" || $request[count($request)-1] == "xml"){
			return "application/".$request[count($request)-1];
		} 	
		else if(isset($_SERVER['HTTP_ACCEPT'])){
			return $_SERVER['HTTP_ACCEPT'];
		}
		return "application/xml";
	}
	
	/**
	 * Function to get posted data
	 * @access public
	 * @param - 
	 * @return array with data
	 */
	function getPostedData(){
		if($this->getRequestType() == 'post' AND !empty($_POST)){
			return $_POST;
		}
		else if($this->getRequestType() == 'put' || $this->getRequestType() == 'delete'){
			$postedContent = file_get_contents('php://input');
			$postedContent = explode('&', $postedContent);
			$returnArray = array();
			foreach($postedContent as $value){
				$temp = explode('=', $value);
				$returnArray[$temp[0]] = $temp[1];
			}
			return $returnArray;
		}
		return null;
		
	}
	
	function validRequestedResource(){
		$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
		
			if(count($request) == 1 AND $request[0] == "positions"){
				return true;
			}
			else if($request[0] == "position" AND isset($request[1]) AND isset($request[2])){
				if($request[1] == "producer" AND is_int((int)$request[2])){
					return true;
				}
			}
			return false;
	}
}
?>